package com.by.Service.impl;

import com.by.Service.MinioService;
import com.by.entity.Minio;
import com.google.common.net.HttpHeaders;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import static io.minio.BucketExistsArgs.builder;

/**
 * @author 江俊俊
 * @version 1.0
 * @description
 * @date 2025/4/11 11:28
 * @since JDK1.8
 */
@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    Minio minio;

    @PostConstruct
    void  init(){
        try {
            boolean exists = minioClient.bucketExists(builder().bucket(minio.getBucketName()).build());
            //如果桶不存在，创建桶
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minio.getBucketName()).build());
            }
        }catch (Exception e){
            throw new RuntimeException("桶创建失败");
        }
    }

    @Override
    public String upload(MultipartFile file) {
        try {

            //获取时间
            String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            //UUID
            String uuid = UUID.randomUUID().toString();
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            int dotIndex = originalFilename.lastIndexOf(".");
            if (dotIndex > 0) {
                extension = originalFilename.substring(dotIndex);
            }
            String newFileName = uuid + extension;
            String fileName = dateTime + "/" + newFileName;
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minio.getBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            String url = minio.getUrl() + "/" + minio.getBucketName() + "/" + fileName;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }
    }

    @Override
    public ResponseEntity<InputStreamResource> download(String url) throws Exception {
        String objectUrl = url.split(minio.getBucketName() + "/")[1];
        InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(minio.getBucketName())
                        .object(objectUrl)
                        .build()
        );
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + url + "\"")
                .body(new InputStreamResource(inputStream));
    }

    @Override
    public int delete(String url) {

        String objectUrl = url.split(minio.getBucketName() + "/")[1];
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(minio.getBucketName())
                    .object(objectUrl)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件删除失败");
        }
        return 1;
    }
}
